import { useQuery } from "@tanstack/react-query";
import { appAPI } from "@/api";
import type { AppConfigResponseData } from "@/types/response";

export const useAppConfig = () => {
  return useQuery<AppConfigResponseData>({
    queryKey: ["appConfig"],
    queryFn: async (): Promise<AppConfigResponseData> => {
      const response = await appAPI.appConfig();
      // 将 appConfig 保存到 localStorage
      if (response.data) {
        localStorage.setItem("appConfig", JSON.stringify(response.data));
      }
      return response.data;
    },
    staleTime: 5 * 60 * 1000, // 5分钟
    gcTime: 10 * 60 * 1000, // 10分钟
  });
};

// 从 localStorage 获取 appConfig 的工具函数
export const getAppConfigFromStorage = (): AppConfigResponseData | null => {
  try {
    const stored = localStorage.getItem("appConfig");
    return stored ? JSON.parse(stored) : null;
  } catch {
    return null;
  }
};
